//
//  MinePublishViewController.swift
//  House
//
//  Created by 吕品 on 2016/9/22.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

import UIKit
import MBProgressHUD
public enum PublishType: Int {
    case wantRent = 0 //租房委托
    case rent = 1   //出租委托
    case buyHouse = 2 //买房委托
    case sellHouse = 3//卖房委托
}

class MinePublishViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {

    fileprivate let titleArray = ["租房委托", "出租委托", "买房委托", "卖房委托"]
    fileprivate var buttonArray = [UIButton]()
    fileprivate var tableViewArray = [UITableView]()
    fileprivate var underView = UIView()
    fileprivate var scrollView = UIScrollView()
    var naviBar = BaseTitleNavigationBar()
    
    fileprivate var zufangArray = [MinePublishModel]()
    fileprivate var zhucuArray = [MinePublishPicModel]()
    fileprivate var maifangArray = [MinePublishModel]()
    fileprivate var sellHouseArray = [MinePublishPicModel]()
    fileprivate var dataArray = [[AnyObject]]()
    fileprivate var selectedTag = 0
    private func fetchDataWith(_ Type: PublishType = .wantRent) -> Swift.Void {
        let userid = UserInfoManager.shared().uid
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.mode = .text
        hud.label.text = "加载中"
        self.dataArray[Type.rawValue].removeAll()
        switch Type {
        case .wantRent:
            let urlStr = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_my_zufang/userid/%@/page/1", userid!)
            NetRequest.getInformationWithGetMethod(withUrl: urlStr, success: { (task, response) in
                    print(response)
                if response is NSDictionary {
                    let responseObj = response as! NSDictionary
                    if (responseObj["flag"] as! String).description == "1" {
                        let arr = responseObj["zufang"]
                        self.dataArray[Type.rawValue] = MinePublishModel.setValuesAndKeysWith(arr as! [[AnyHashable: Any]]) as! [MinePublishModel]
                        self.hide(withTitle: "加载成功")
                        self.tableViewArray[Type.rawValue].reloadData()

                    } else {
                        self.hide(withTitle: "暂无数据")
                        self.tableViewArray[Type.rawValue].reloadData()

                    }
                }
                }, failure: { (task, error) in
                    self.hide(withTitle: "暂无数据")
            })
        case .rent:
            let urlStr = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_my_chuzu/userid/%@/page/1", userid!)
            NetRequest.getInformationWithGetMethod(withUrl: urlStr, success: { (task, response) in
                print(response)
                if response is NSDictionary {

                    let responseObj = response as! NSDictionary
                    if (responseObj["flag"] as! String).description == "1" {
                        let arr = responseObj["chuzu"]
                        self.dataArray[Type.rawValue] = MinePublishPicModel.setValuesAndKeysWith(arr as! [[AnyHashable: Any]]) as! [MinePublishPicModel]
                        self.hide(withTitle: "加载成功")
                        self.tableViewArray[Type.rawValue].reloadData()

                    } else {
                        self.hide(withTitle: "暂无数据")
                        self.tableViewArray[Type.rawValue].reloadData()

                    }
                }
                }, failure: { (task, error) in
                    print(error)
                    self.hide(withTitle: "暂无数据")

            })
        case .buyHouse:
            let urlStr = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_my_buy/userid/%@/page/1", userid!)
            NetRequest.getInformationWithGetMethod(withUrl: urlStr, success: { (task, response) in
                print(response)
                let responseObj = response as! NSDictionary
                if (responseObj["flag"] as! String).description == "1" {
                let arr = responseObj["maifang"]
                self.dataArray[Type.rawValue] = MinePublishModel.setValuesAndKeysWith(arr as! [[AnyHashable: Any]]) as! [MinePublishModel]
                    self.tableViewArray[Type.rawValue].reloadData()
                    self.hide(withTitle: "加载成功")
                } else {
                    self.hide(withTitle: "暂无数据")
                    self.tableViewArray[Type.rawValue].reloadData()

                }
                }, failure: { (task, error) in
                    print(error)
                    self.hide(withTitle: "暂无数据")

            })
        case .sellHouse:
            let urlStr = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_my_sell/userid/%@/page/1", userid!)
            NetRequest.getInformationWithGetMethod(withUrl: urlStr, success: { (task, reponse) in
                print(reponse)
                let responseObj = reponse as! NSDictionary
                if (responseObj["flag"] as! String).description == "1" {
                let arr = responseObj["maifang"]
                self.dataArray[Type.rawValue] = MinePublishPicModel.setValuesAndKeysWith(arr as! [[AnyHashable: Any]]) as! [MinePublishPicModel]
                    self.hide(withTitle: "加载成功")
                    self.tableViewArray[Type.rawValue].reloadData()
                } else {
                    self.hide(withTitle: "暂无数据")
                    self.tableViewArray[Type.rawValue].reloadData()

                }
                }, failure: { (task, error) in
                    print(error)
                    self.hide(withTitle: "暂无数据")
            })
        }

    }
    private func reloadData() -> Swift.Void {
        for tableView in tableViewArray {
            tableView.reloadData()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tabBarController?.tabBar.isHidden = true
        didSelectHeaderViewButton(buttonArray[selectedTag])
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        tabBarController?.tabBar.isHidden = false
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        dataArray = [zufangArray, zhucuArray, maifangArray, sellHouseArray]
        view.backgroundColor = .white
        naviBar = BaseTitleNavigationBar.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: 64), withTitleStr: "我的委托")
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(back(tap:)))
        
        naviBar.leftView.addGestureRecognizer(tap)
        view.addSubview(naviBar)
        
        automaticallyAdjustsScrollViewInsets = false
        initHeaderView()//初始化头部view
        createTableView()//创建tableview
//        didSelectHeaderViewButton(buttonArray[0])//默认选择第0个
//        fetchDataWith()
    }

    /// 显示顶部view
    ///
    /// - returns: nil
    private func initHeaderView() -> Swift.Void {
        let header = UIView.init()
        view.addSubview(header)
        header.snp.makeConstraints { (make) in
            make.top.equalTo(view.snp.top).offset(64)
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
        }
        for i in 0 ... 3 {
            let button = UIButton.init(type: .system)
            header.addSubview(button)
            button.tag = i + tagManager
            button.setTitle(titleArray[i], for: .normal)
            button.addTarget(self, action: #selector(MinePublishViewController.didSelectHeaderViewButton(_:)), for: .touchUpInside)
            let width = UIScreen.main.bounds.size.width / 4
            button.frame = .init(x: width * CGFloat.init(i), y: 0, width: width, height: 40)
            button.titleLabel?.font = .systemFont(ofSize: 16)
            button.tintColor = .black
            buttonArray.append(button)
        }
        let grayView = UIView.init()
        grayView.backgroundColor = .gray
        grayView.frame = .init(x: 0, y: 40 - 2, width: UIScreen.main.bounds.size.width, height: 2)
        header.addSubview(grayView)
        underView.frame = .init(x: 0, y: 0, width: UIScreen.main.bounds.size.width / 4, height: 2)
        underView.backgroundColor = .red
        grayView.addSubview(underView)
    }
    private func createTableView() -> Swift.Void {
        view.addSubview(scrollView)
        scrollView.delegate = self
        scrollView.frame = .init(x: 0, y: 104, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - 104.0)
        scrollView.contentSize = .init(width: UIScreen.main.bounds.size.width * 4, height: UIScreen.main.bounds.size.height - 64 - 40)
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        for i in 0 ... 3 {
            let tableView = UITableView.init(frame: CGRect.init(x: CGFloat.init(i) * UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width, height: scrollView.mj_h), style: .grouped)
            if i % 2 == 0 {
                tableView.register(MinePublishTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(MinePublishTableViewCell.self))
            } else {
                tableView.register(MinePublishDetailPictureTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(MinePublishDetailPictureTableViewCell.self))
            }

            tableView.register(MinePulishHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: NSStringFromClass(MinePulishHeaderFooterView.self))
            tableView.delegate = self
            tableView.dataSource = self
            scrollView.addSubview(tableView)
            tableViewArray.append(tableView)
        }
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray[tableViewArray.index(of: tableView)!].count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let index = tableViewArray.index(of: tableView)!
        if index % 2 == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(MinePublishTableViewCell.self)) as! MinePublishTableViewCell
            cell.selectionStyle = .none
            cell.model = dataArray[index][indexPath.section] as! MinePublishModel
            cell.reloadData()
            return cell
        } else {
            let picCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(MinePublishDetailPictureTableViewCell.self)) as! MinePublishDetailPictureTableViewCell
            picCell.selectionStyle = .none
            picCell.model = dataArray[index][indexPath.section] as! MinePublishPicModel
            return picCell
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let index = tableViewArray.index(of: tableView)!
        if index % 2 == 0 {
            return 44 * 7
        } else {
            return 150
        }
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: NSStringFromClass(MinePulishHeaderFooterView.self)) as! MinePulishHeaderFooterView
        footerView.deleteButton.addTarget(self, action: #selector(deletePublish(_:)), for: .touchUpInside)
        footerView.deleteButton.tag = tableViewArray.index(of: tableView)! * 100 + section
        footerView.editButton.addTarget(self, action: #selector(editPublish(_:)), for: .touchUpInside)
        footerView.editButton.tag = tableViewArray.index(of: tableView)! * 1000 + section
        return footerView
    }

    @objc func editPublish(_ button: UIButton) -> Swift.Void {

        let tableViewTag = button.tag / 1000
        let section = button.tag % 1000
        if tableViewTag == 0 || tableViewTag == 2 {
            let model = dataArray[tableViewTag][section] as! MinePublishModel
            if tableViewTag == 0 {
                let rentHouseVC = RentHouseEntrustViewController.init()
                rentHouseVC.model = model
                navigationController!.pushViewController(rentHouseVC, animated: true)
            } else {
                let buyHouseVC = BuyHouseEntrustViewController.init()
                buyHouseVC.model = model
                navigationController!.pushViewController(buyHouseVC, animated: true)
            }
        } else {
            let model = dataArray[tableViewTag][section] as! MinePublishPicModel
            if model.status == "3" {
                let hud = MBProgressHUD.showAdded(to: view, animated: true)
                hud.mode = .text
                hud.label.text = "此委托不能被修改"
                DispatchQueue.main.async {
                    hud.hide(animated: true, afterDelay: 1)
                }
                return
            } else {
                if tableViewTag == 1 {
                    let rentVC = RentEntrustViewController.init()
                    rentVC.model = model
                    navigationController?.pushViewController(rentVC, animated: true)
                } else {
                    let sellHouseVC = SellHouseEntrustViewController.init()
                    sellHouseVC.model = model
                    navigationController!.pushViewController(sellHouseVC, animated: true)
                }
            }
        }
    }
    @objc func deletePublish(_ button: UIButton) -> Swift.Void {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.mode = .text
        hud.label.text = "正在删除"
        let tableViewTag = button.tag / 100
        selectedTag = tableViewTag
        let section = button.tag % 100
        var url = ""
        let uid = UserInfoManager.shared().uid
        switch tableViewTag {
        case 0:
            let model = dataArray[tableViewTag][section] as! MinePublishModel
            url = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_del_zfwt/userid/%@/id/%@", uid!, (model.id?.description)!)
        case 1:
            let model = dataArray[tableViewTag][section] as! MinePublishPicModel
            url = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_del_chuzu/userid/%@/id/%@", uid!, (model.itemid?.description)!)
        case 2:
            let model = dataArray[tableViewTag][section] as! MinePublishModel
            url = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_del_mfwt/userid/%@/id/%@", uid!, (model.id?.description)!)
        case 3:
            let model = dataArray[tableViewTag][section] as! MinePublishPicModel
            url = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/App_del_maifang/userid/%@/id/%@", uid!, (model.itemid?.description)!)
        default: break
        }
        NetRequest.getInformationWithGetMethod(withUrl: url, success: { (task, response) in
            print(response)
            let reponseObj = response as! NSDictionary
            if (reponseObj["flg"] as! NSNumber).description == "1" {
                self.hide(withTitle: "删除成功")
                self.didSelectHeaderViewButton(self.buttonArray[tableViewTag])
            } else {
                self.hide(withTitle: "删除失败")
            }
        }) { (task, error) in
            print(error)
            self.hide(withTitle: "删除失败")
        }

    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 50
    }
    @objc private func didSelectHeaderViewButton(_ button: UIButton) -> Swift.Void {
        let index = buttonArray.index(of: button)
        selectedTag = index!
        fetchDataWith(PublishType.init(rawValue: index!)!)
        for button in buttonArray {
            button.tintColor = .black
        }
        button.tintColor = .red
        UIView.animate(withDuration: 0.2) {
            let index = self.buttonArray.index(of: button)
            self.underView.center.x = button.center.x
            self.scrollView.setContentOffset(CGPoint.init(x:CGFloat.init(index!) * self.scrollView.mj_w , y: 0), animated: true)
        }
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView.isEqual(self.scrollView) {
            let index = scrollView.contentOffset.x / scrollView.mj_w
            let index1 = Int.init(index)
            didSelectHeaderViewButton(self.buttonArray[index1])
        }
    }
    //    func scrollViewDidEndScroll(_ scrollView: UIScrollView) {
    //
    //    }
    @objc func back(tap: UITapGestureRecognizer) -> Void {
        self.navigationController!.popViewController(animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
